package com.example.activemq.com.example.activemq.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @ Author     ：scw
 * @ Date       ：Created in 上午 11:30 2019/7/29 0014
 * @ Description：TOPIC01消息消费者
 * @ Modified By：
 * @Version: $version$
 */
public class TopicConsumer1 {//定义ActivMQ的连接地址
    private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
    //定义发送消息的队列名称
    private static final String TOPIC_NAME = "topic";
    public static void main(String[] args) throws JMSException, IOException {
        System.out.println("TOPIC1*******消费者的方式");
        //创建连接工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //创建连接
        Connection connection = activeMQConnectionFactory.createConnection();
        //打开连接
        connection.start();
        //创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //创建队列目标
        Topic topic=session.createTopic(TOPIC_NAME);
        //创建消费者
        MessageConsumer consumer1 = session.createConsumer(topic);
        //receive()方法，可以有时间等待，也可以一直等待，receive()，receive(4000L)4秒等待时间
        /*while(true){
           TextMessage textMessage= (TextMessage) consumer.receive();
           if(null!=textMessage){
               System.out.println("*******消费者接收到消息"+textMessage.getText());
           }else{
               break;
           }
        }*/
        consumer1.setMessageListener(message -> {
            if (null!= message && message instanceof TextMessage){
                TextMessage textMessage= (TextMessage) message;
                try {
                    System.out.println("*******消费者TOPIC1接收到消息"+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        //保证控制台一直在运行着
        System.in.read();//监听消费者
        consumer1.close();
        session.close();
        connection.close();

    }
}